package com.itcast.filter;

import com.itcast.utils.CurrentHolder;
import com.itcast.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@WebFilter("/*")
@Slf4j
public class FilterTilaasDemo implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("初始化过滤器");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("过滤器开始工作");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径
        String url = request.getRequestURL().toString();
        if (url.contains("/login")){
            log.info("登录操作");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //验证token是否为空
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()){
            log.info("token为空");
            //设置401状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        try {
           Claims claims = JwtUtils.parseJWT(token);
           Integer empId = Integer.valueOf(claims.get("id").toString());
           //设置员工id
            log.info("过滤器中-线程-设置员工ID{}",empId);
           CurrentHolder.setCurrentId(empId);
        } catch (Exception e) {
            log.info("token解析失败");
            //设置401状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        log.info("验证成功");
        //  放行
        filterChain.doFilter(servletRequest,servletResponse);

        //销毁线程存储
        CurrentHolder.remove();
    }

    @Override
    public void destroy() {
        log.info("销毁过滤器");
        Filter.super.destroy();
    }
}
